using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class AnimationManager : MonoBehaviour
{
	public Animator animator;
	public List<string> animationStack = new List<string>();
	public bool CR_Running;

	public string animationToAdd;

	void Awake()
	{
		animator = GetComponent<Animator>();
	}

	// Use this for initialization
	void Start ()
	{
		CR_Running = false;
	}
	// Update is called once per frame
	void Update ()
	{
		if(CR_Running == false)
			PlayAnimationStack();
		if(animationToAdd != "")
			AddAnimation();
	}

	void PlayAnimationStack()
	{
		if(animationStack.Count > 1)
		{
			StartCoroutine(PlayAnimationOnce(animationStack[0]));
			animationStack.RemoveAt(0);
		}
		else
			StartCoroutine(PlayAnimationLoop(animationStack[0]));
	}

	void AddAnimation()
	{
		animationStack.Add(animationToAdd);
		animationToAdd = "";
	}

	public void SetAnimation(string animToAdd)
	{
		animationStack.Add(animToAdd);
	}

	public void ClearStack()
	{
		for(int i = 0; i < animationStack.Count; i++)
		{
			if(animationStack.Count > 1)
				animationStack.RemoveAt(0);
		}
		StartCoroutine(PlayAnimationLoop(animationStack[0]));
	}

	IEnumerator PlayAnimationOnce(string anim)
	{
		CR_Running = true;
		animator.SetBool(anim, true);
		yield return new WaitForSeconds(2);
		animator.SetBool(anim, false);
		CR_Running = false;
	}

	IEnumerator PlayAnimationLoop(string anim)
	{
		animator.SetBool(anim, true);
		yield return null;
	}
}

